package com.cloudfun.campusshare.device.protocol.decoder;

import com.cloudfun.campusshare.device.protocol.response.BaseMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

import java.util.List;

/**
 * Created by Huqin on 2020/1/3
 */
@Slf4j
public abstract class ByteToMessageDecoder<T extends BaseMessage> {

    protected abstract List<FieldDecoder<T>> fieldDecoderList();

    protected abstract T prepare();

    protected boolean preProcessBeforeDecode(byte[] data, T obj) {
        return false;
    }

    public final T decode(byte[] data) {
        T obj = prepare();
        boolean preProcessSuc = preProcessBeforeDecode(data, obj);
        if (preProcessSuc) {
            return obj;
        }
        for (FieldDecoder<T> fieldDecoder : fieldDecoderList()) {
            int start = fieldDecoder.start();
            int length = fieldDecoder.length();
            byte[] fieldData = ArrayUtils.subarray(data, start, start + length);
            fieldDecoder.decode(fieldData, obj);
        }
        return obj;
    }

}
